package com.joymeter.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName DruidQueryUtil
 * @Description TODO
 * druid数据库查询
 *
 * @Author liang
 * @Date 2018/8/6 15:25
 * @Version 1.0
 **/
public class DruidQueryUtil {
    private static final String QUERY_URL = "http://47.93.21.73:8082/druid/v2/sql/";

    /**
     * 查询设备最新读数
     * @param deviceId
     * @return
     */
    public static String queryData(String deviceId){
        try {
            String QUERY_DATA_SQL ="{\"query\":\"select data   from  dataInfo where  event = 'data' and deviceId =  '"+deviceId +"'  order by __time desc limit 1 \"}";
            String result = HttpClient.sendPost(QUERY_URL, QUERY_DATA_SQL);
            JSONArray array = JSONArray.parseArray(result);
            JSONObject jsonObject = (JSONObject) array.get(0);
            String data = jsonObject.getString("data");
            return data;
        }catch (Exception e){
            return null;
        }

     }

    /**
     * 查询设备最新读数和时间
     * @param deviceId
     * @return
     */
    public static JSONObject queryDataAndTime(String deviceId){
        try {
            String QUERY_DATA_SQL ="{\"query\":\"select data , ( __time + INTERVAL '8' HOUR)  as updateTime    from  dataInfo where  event = 'data' and deviceId =  '"+deviceId +"'  order by __time desc limit 1 \"}";
            String result = HttpClient.sendPost(QUERY_URL, QUERY_DATA_SQL);
            JSONArray array = JSONArray.parseArray(result);
            JSONObject jsonObject = (JSONObject) array.get(0);
            String data = jsonObject.getString("data");
            String time = jsonObject.getString("updateTime");
            String formatTime = time.replace('T',' ');
            String substring = formatTime.substring(0, 19);
            JSONObject resultJson = new JSONObject();
            resultJson.put("data",data);
            resultJson.put("time",substring);
            return resultJson;
        }catch (Exception e){
            return null;
        }

    }
}
